<template>
  <yt-page :title="title" :rightData="rightData" scroll>
    <yt-cell label="事故类型" :value="accident.accident_type"></yt-cell>
    <yt-cell label="事发地点" :value="accident.accident_place"></yt-cell>
    <yt-cell label="事发时间" :value="accident.createdAt | formatTime"></yt-cell>
    <yt-cell label="附近逃生点" v-if="accident.gridId" isLink @click="onClickEscapePointsNav"></yt-cell>
    <yt-cell label="周边视频" v-if="accident.gridId" isLink @click="onClickVideoNav"></yt-cell>
    <yt-cell label="事故详情" isLink @click="onClickAccidentProfileNav"></yt-cell>
    <yt-split></yt-split>
    <yt-cell v-for="(item, index) in navigations" :key="index" :label="item.label" :icon="item.icon" isLink @click="onClickNavigation(item)"></yt-cell>
  </yt-page>
</template>

<script>
import { commonApi } from '@/common/api/commonApi.js'
import { ReplaceDictionary } from '@/common/utils/index.js'
import { bridge } from '@/common/plugin/utils/bridge'
import {
  EscapePoints,
  Videos,
  AccidentProfile,
  Preliminary,
  EarlyDisposal,
  CommandDispatch,
  InfoRegister,
  ProcessRecord
} from './router'

const SERVER = ''
const SERVER_DEFAULT = { protocol: 'rtmp', ip: '218.92.104.98', port: '1935', beforeDes: '/live/' }

export default {
  data() {
    return {
      SERVER,
      title: '',
      rightData: [
        {
          text: '直播',
          click: async () => {
            let addr = await this.getStreamAddress()
            if (addr) {
              // todo 还需要成功掉起直播回调
              await this.updateAddreesState(addr, 1)
              bridge.Live(addr, () => {
                // 退出直播回调,更新状态
                this.updateAddreesState(addr, 0)
              })
            } else {
              // 获取不到地址，就说明地址全部占线了
            }
          }
        }
      ],
      id: null,
      nextPageQuery: {},
      accident: {},
      navigations: [
        {
          icon: require('./img/chubu.png'),
          label: '初步预判',
          path: Preliminary.path
        },
        {
          icon: require('./img/xianqi.png'),
          label: '先期处置',
          path: EarlyDisposal.path
        },
        {
          icon: require('./img/zhihui.png'),
          label: '指挥调度',
          path: CommandDispatch.path
        },
        {
          icon: require('./img/dengji.png'),
          label: '信息登记',
          path: InfoRegister.path
        },
        {
          icon: require('./img/guocheng.png'),
          label: '过程记录',
          path: ProcessRecord.path
        }
      ]
    }
  },
  async activated() {
    let { id, title } = this.$route.query
    this.id = id
    this.title = title

    await this.fetchLiveAddress()
    this.fetchData(id)
  },
  methods: {
    async fetchData(id) {
      let p = [
        commonApi.dictionary('Accident_type'),
        commonApi.searchById('yj_emergency_information', id)
      ]
      let [accidentTypeDic, accident] = await Promise.all(p)

      this.nextPageQuery = {
        id: accident.id,
        accident_type: accident.accident_type
      }

      this.accident = ReplaceDictionary(accident, {
        accident_type: accidentTypeDic
      })
    },
    async fetchLiveAddress() {
      let res = await commonApi.search('sys_setting', { equalTo: { name: '直播流媒体地址' } })
      let { protocol, ip, port, beforeDes } = (res.length ? res[0] : SERVER_DEFAULT)
      this.SERVER = `${protocol}://${ip}:${port}${beforeDes}`
    },
    onClickNavigation(item) {
      // 必须启用某一预案，才可以先期处置
      if (item.label === '先期处置') {
        if (!this.accident.reservePlan) {
          this.$Toast('请先进入初步预判中，匹配预案!')
          return
        }
      }

      this.routerLink(item.path)
    },
    onClickVideoNav() {
      this.routerLink(
        Videos.path,
        this.accident.gridId ? { gridId: this.accident.gridId.id } : undefined
      )
    },
    onClickEscapePointsNav() {
      this.routerLink(EscapePoints.path)
    },
    onClickAccidentProfileNav() {
      this.routerLink(AccidentProfile.path)
    },
    routerLink(path, query = this.nextPageQuery) {
      this.$router.$push({
        path: path,
        query: query
      })
    },
    async getStreamAddress() {
      const addrsTotalMax = 4 // 支持同时播放的最大数量，暂时这样，有可能改动

      let accidentId = this.$route.query.id
      let addrs = await commonApi.search('yj_stream_address', {
        equalTo: { accident_id: accidentId },
        ascending: ['address']
      })

      if (addrs.length) {
        // 当前事故下，有流媒体地址
        let canUseAddrs = addrs.filter(v => v.state === 0)
        if (canUseAddrs.length) {
          // 有地址，且有没被占线的地址
          let canUseAddrssAfter = _.sortBy(canUseAddrs, item => item.address)
          return canUseAddrssAfter[0].address
        } else if (addrs.length < addrsTotalMax) {
          // 有地址，全部占线
          let addr = await this.creatStreamAddress(addrs.length + 1)
          return addr
        } else {
          this.$Toast('当前直播地址全占线，请等待！', 'tool')
        }
      } else {
        // 当前事故下，没有流媒体
        let addr = await this.creatStreamAddress()
        return addr
      }
    },
    async creatStreamAddress(number) {
      let accidentId = this.$route.query.id
      let currentAddr = this.getAddress(number)
      await commonApi.save('yj_stream_address', {
        accident_id: commonApi.createInstance(
          'yj_emergency_information',
          accidentId
        ),
        address: currentAddr,
        state: 0
      })
      return currentAddr
    },
    getAddress(number = 1) {
      let accidentId = this.$route.query.id
      // 目前前端生成流媒体地址的规则，是固定部分加上地址序号，每个事故下最多允许4个流媒体地址同时在线
      return `${this.SERVER}${accidentId}/${number}`
    },
    async updateAddreesState(addr, state) {
      let item = await commonApi.searchFirst('yj_stream_address', {
        equalTo: { address: addr }
      })
      commonApi.save('yj_stream_address', { ...item, state })
    }
  }
}
</script>
